<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">

      <!-- <el-form-item label="用户id" prop="value">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="回收员手机号" prop="value">
        <el-input
          v-model="queryParams.riderPhone"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="订单编号" prop="value">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="value">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="item,ix in statusTxt"
            :key="ix"
            :label="item.label"
            :value="item.value"
          />

        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          v-hasPermi="['huishou:settlementOrder:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="openExcelFn"
        >批量导出
        </el-button>

        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入
        </el-button>

        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
        <!-- <el-button
          v-hasPermi="['huishou:recoveryVehicle:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button> -->

      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="订单编号" align="center" prop="orderNo"/>
      <!-- <el-table-column label="预约订单id" align="center" prop="appointOrderId" />
      <el-table-column label="用户id" align="center" prop="userId" /> -->
      <el-table-column label="结算重量" align="center" prop="weightTal"/>
      <el-table-column label="结算金额" align="center" prop="amountTal"/>
      <el-table-column label="回收员" align="center" prop="riderName"/>
      <el-table-column label="回收员手机号" align="center" prop="riderPhone"/>
      <el-table-column label="支付图片" align="center" prop="imgUrl" width="160">
        <template slot-scope="scope">
          <img :src="scope.row.imgUrl" style="width: 80px;" alt="">
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" disabled placeholder="请选择">
            <el-option
              v-for="item,ix in statusTxt"
              :key="ix"
              :label="item.label"
              :value="item.value"
            />

          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="更新时间" align="center" prop="updateTime"/>

      <el-table-column label="操作" align="center" class-name="small-padding" width="220">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['huishou:settlementOrder:query']"
            size="mini"
            type="success"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >详情
          </el-button>
          <el-button
            v-hasPermi="['huishou:recoveryVehicle:remove']"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="导出表格" :visible.sync="openExcel" append-to-body>
      <div>
        <el-date-picker
          v-model="date1"
          type="date"
          range-separator="至"
          placeholder="选择开始日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="dateChange">
        </el-date-picker>
        -
        <el-date-picker
          v-model="date2"
          type="date"
          range-separator="至"
          placeholder="选择结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="dateChange">
        </el-date-picker>
        <!-- <el-radio v-model="excelType" label="1">导出当前页</el-radio>
        <el-radio v-model="excelType" label="2">导出最新500条</el-radio> -->
      </div>
      <div style="margin: 20px;">(时间跨度不能超过一年)</div>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitExcel">确 定</el-button>
        <el-button @click="openExcel = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改推荐管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="100px">

        <!-- <el-form-item label="id">
          <el-input v-model="form.id" placeholder="请输入" clearable :readonly="readonly" />
        </el-form-item> -->
        <el-form-item label="订单编号">
          <el-input v-model="form.orderNo" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>
        <!-- <el-form-item label="预约订单id">
          <el-input v-model="form.appointOrderId" placeholder="请输入" clearable :readonly="readonly" />
        </el-form-item>
        <el-form-item label="用户id">
          <el-input v-model="form.userId" placeholder="请输入" clearable :readonly="readonly" />
        </el-form-item> -->
        <el-form-item label="结算重量">
          <el-input v-model="form.weightTal" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>
        <el-form-item label="结算金额">
          <el-input v-model="form.amountTal" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>

        <el-form-item label="回收员手机号">
          <el-input v-model="form.riderPhone" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>
        <el-form-item label="状态" prop="value">
          <el-select v-model="form.status" placeholder="请选择" :disabled="readonly">
            <el-option
              v-for="item,ix in statusTxt"
              :key="ix"
              :label="item.label"
              :value="item.value"
            />

          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form.createTime" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="form.updateTime" placeholder="请输入" clearable :readonly="readonly"/>
        </el-form-item>
        <el-form-item label="支付图片">
          <el-image
            v-if="form.imgUrl"
            style="width: 100px; height: 100px"
            :src="form.imgUrl"
          />
          <span v-else>暂无图片</span>
        </el-form-item>

        <el-form-item label="结算废品列表信息" label-width="200px">
          <el-table v-loading="loading" border :data="form.hsUserWasteVoList" style="width: 60vw;">
            <!-- <el-table-column label="编号" align="center" prop="id" /> -->
            <el-table-column label="预约订单id" align="center" prop="orderId"/>
            <!-- <el-table-column label="编号" align="center" prop="orderType" /> -->
            <!-- <el-table-column label="废品分类id" align="center" prop="categorizeId" /> -->
            <el-table-column label="废品分类名" align="center" prop="categorizeName"/>
            <el-table-column label="废品重量" align="center" prop="weight"/>
            <el-table-column label="废品金额" align="center" prop="amount"/>
            <el-table-column label="价格" align="center" prop="price"/>
            <el-table-column label="结算废品图片" align="center" prop="imgUrl" width="160">
              <template slot-scope="scope">
                <img :src="scope.row.imgUrl" style="width: 80px;" alt="">
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
          </el-table>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="import_dialog.title" :visible.sync="import_dialog.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="import_dialog.headers"
        :action="import_dialog.url + '?updateSupport=' + import_dialog.updateSupport"
        :disabled="import_dialog.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="import_dialog.updateSupport"/>-->
          <!--            是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="import_dialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  updateSettlementOrder,
  addSettlementOrder,
  settlementOrderlist,
  settlementOrderDetail,
  settlementOrderDel
} from '@/api/getdata/getdata'
import {getToken} from "@/utils/auth";

export default {
  name: 'Settlement',
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // // 选中数组
      // ids: [],
      // // 非单个禁用
      // single: true,
      // // 非多个禁用
      // multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 推荐管理表格数据
      dataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openExcel: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // id: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        // spuId: [
        //   { required: true, message: '商品id不能为空', trigger: 'blur' }
        // ],

      },
      props: {
        multiple: true,
        value: 'id'
      },
      options: [],
      imgjson: null,
      riderlist: [],
      statusTxt: [
        {label: '全部', value: ''},
        {label: '结算中,未确认', value: 0},
        {label: '已确认通过，未支付', value: 1},
        {label: '确认不通过', value: 2},
        {label: '已支付，待确认', value: 3},
        {label: '支付成功,完结', value: 4},
        {label: '支付失败,', value: 5},
        {label: '失败，完结', value: 6}
        // { label: '待评价', value: 7 },
        // { label: '服务失败，已评价', value: 8 },
        // { label: '超时', value: 9 }
      ],
      readonly: true,
      excelType: '1',
      date1: null,
      date2: null,
      startPickerTime: '',
      pickerOptions: {
        disabledDate: time => { // 通过disabledDate设置某个时间范围是否禁用可选
          const today = new Date()
          const maxDate = new Date(today)
          return time.getTime() > maxDate.getTime()
        }
      },
      import_dialog: {
        open: false,
        title: '结算单新增导入',
        headers: {Authorization: 'Bearer ' + getToken()},
        url: process.env.VUE_APP_BASE_API + '/system/huishou/settlementOrder/import',
        isUploading: false
      }
      // pickerOptions: {
      //   // 选择第一次时间时触发
      //   onPick: obj => {
      //     // obj对象格式为 {
      //     // "minDate": "2023-12-31T16:00:00.000Z格式",
      //     // "maxDate": "2024-01-19T16:00:00.000Z"
      //     // }
      //     this.startPickerTime = new Date(obj.minDate).getTime()
      //   },
      //   disabledDate: time => { // 通过disabledDate设置某个时间范围是否禁用可选
      //     if (this.startPickerTime) {
      //       const today = new Date()
      //       const maxDate = new Date(today)
      //       // 时间范围（我这为30天）
      //       const timeFrame = 24 * 3600 * 1000 * 30
      //       // minFrame为最小选中范围
      //       const minFrame = this.startPickerTime - timeFrame
      //       // maxFrame为最大选中的范围
      //       var maxFrame = this.startPickerTime + timeFrame
      //       if (maxFrame > maxDate.getTime()) {
      //         maxFrame = maxDate.getTime()
      //       }
      //       const pickerType = time.getTime() > maxFrame || time.getTime() < minFrame
      //       // pickerType为布尔值，返回false或true；
      //       return pickerType
      //     } else {
      //       const today = new Date()
      //       const maxDate = new Date(today)
      //       return time.getTime() > maxDate.getTime()
      //     }
      //   }
      // }

    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      settlementOrderlist(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        status: 0
      }
      this.imgjson = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // /** 重置按钮操作 */
    // resetQuery() {
    //   this.resetForm('queryForm')
    //   this.handleQuery()
    // },
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length !== 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '创建'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id
      await settlementOrderDetail(id).then(response => {
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '详情'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          // <el-image :src="JSON.parse(row.imgUrl)[0].url" />
          if (this.imgjson) {
            this.form.imgUrl = JSON.parse(this.imgjson)[0].url
          }
          this.form.hsUserWasteBoList = this.form.hsUserWasteVoList
          if (this.form.id != null) {
            updateSettlementOrder(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addSettlementOrder({...this.form}).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    getProductIds(ids) {
      const arr = []
      for (let i = 0; i < ids.length; i++) {
        const els = ids[i]
        arr.push(els[els.length - 1])
      }
      console.log(arr)
      return arr
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(() => {
        this.loading = true
        return settlementOrderDel(ids)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    },
    dateChange(date) {
      // console.log(date)
      if (!date) {
        this.startPickerTime = ''
      }
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      // var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      // var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      // var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D
    },

    openExcelFn() {
      this.openExcel = true
      const B = Date.parse(new Date())
      const timeFrame = 24 * 3600 * 1000 * 30
      const A = B - timeFrame
      this.date1 = this.timestampToTime(A)
      this.date2 = this.timestampToTime(B)
    },
    submitExcel() {
      if (!this.date1) {
        this.$modal.msgSuccess('请选择开始时间')
        return
      }
      if (!this.date2) {
        this.$modal.msgSuccess('请选择结束时间')
        return
      }
      var timestamp = Date.parse(new Date(this.date1))
      var timestamp2 = Date.parse(new Date(this.date2))
      if (timestamp > timestamp2) {
        this.$modal.msgSuccess('开始时间不能大于结束时间')
        return
      }
      const timeFrame = 24 * 3600 * 1000 * 365
      const and = timestamp2 - timestamp
      if (and > timeFrame) {
        this.$modal.msgSuccess('时间区间不能超过一年')
        return
      }
      this.handleExport(timestamp, timestamp2)
      console.log(timestamp, 'this.data1.getTime()')
      // if (!!this.date2 && this.date2.length > 0) {
      //   const obj = {
      //     startTime: this.date2[0],
      //     endTime: this.date2[1]
      //   }
      //   this.handleExport(obj)
      //   this.openExcel = false
      // } else {
      //   this.$modal.msgSuccess('请选择导出时间段')
      // }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.import_dialog.title = '结算单新增导入'
      this.import_dialog.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/huishou/settlementOrder/template', {}, `结算订单导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.import_dialog.open = false
      this.import_dialog.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.import_dialog.isUploading = true
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导出按钮操作 */
    handleExport(t1, t2) {
      // ...this.queryParams
      // const params = {
      //   startTime: this.date1,
      //   endTime: this.date2
      // }
      const params = {
        pageNum: 1,
        pageSize: 200,
        startTime: this.date1,
        endTime: this.date2

      }
      // console.log(params)
      // return
      this.download('system/huishou/settlementOrder/export', {
        ...params
      }, `回收结算订单_${new Date().getTime()}.xlsx`)
    }

  }
}
</script>
